package com.yboot.ssocas.login;

import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.util.AssertionHolder;
import org.jasig.cas.client.validation.Assertion;

import javax.servlet.http.HttpServletRequest;

public class CASUtil {
    /**
     * 从cas中获取用户名
     *
     * @param request
     * @return
     */
    public static String getAccountNameFromCas(HttpServletRequest request) {
        try {
            //自定义拦截器使用如下方式获取 assertion
            //Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
            //自带拦截器使用此方式   获取 assertion
            Assertion assertion = AssertionHolder.getAssertion();
            if (assertion != null) {
            // 如果存在assertion，即认为这是一个已通过认证的请求，予以放行
                AttributePrincipal principal = assertion.getPrincipal();
                return principal.getName();
            } else return null;
        }catch (Exception e){
            e.printStackTrace();
        return null;
        }
    }

}
